<?php

/**
 * Api-模型
 */
class Api {

    const exp = 300;
    const API_RESPONSE_JSON = 'json_object';
    const API_REQUEST_METHOD_GET = 'get';
    const API_REQUEST_METHOD_POST = 'post';

    public static function getToken() {
        global $config;
        $filename = APP_PATH . 'cache/accesstoken.cache';
        if (is_file($filename) && (time() - filemtime($filename)) < self::exp) {
            $accesstoken = file_get_contents($filename);
            return $accesstoken;
        } else {
            $curlRet = Curl::get($config->api->api_root . '/auth/accessToken/eUGhdvpDDpC16iUXqfMsc3ntl/');
            $rt = json_decode($curlRet);
            if (NULL !== $rt) {
                file_put_contents($filename, $rt->retmsg->access_token);
                return $rt->retmsg->access_token;
            } else {
                Util::log('ApiToken error -> ' . $config->api->api_root . '/auth/accessToken/eUGhdvpDDpC16iUXqfMsc3ntl/' . $curlRet);
                return FALSE;
            }
        }
    }

    /**
     * 发起Api调用
     * @param type $uri
     * @param type $params
     * @param type $method
     */
    public static function call($uri, $params = array(), $method = self::API_REQUEST_METHOD_GET, $responseType = self::API_RESPONSE_JSON) {
        global $config;
        $url = $config->api->api_root . $uri;
        if ($method == self::API_REQUEST_METHOD_GET) {
            // get
            $requestURI = $url . '?token=' . Api::getToken() . Api::packParam($params);
            $ret = Curl::get($requestURI);
        } else {
            // post
            $requestURI = $url . '?token=' . Api::getToken();
            $ret = Curl::post($requestURI, $params);
        }
        # echo $requestURI;
        if ($responseType == self::API_RESPONSE_JSON) {
            return json_decode($ret);
        }
        return $ret;
    }

    /**
     * 打包参数
     * @param type $params
     */
    public static function packParam($params) {
        $str = '';
        foreach ($params as $key => $value) {
            $str .= "&$key=$value";
        }
        return $str;
    }

}
